<?php
/**
 * Created by PhpStorm.
 * User: kun
 * Date: 23/6/19
 * Time: 21:01
 */

namespace app\admin\controller;

use app\common\lib\IAuth;
use think\Controller;
use think\Exception;
use think\Session;

class Login extends Base
{
    public function _initialize() //继承覆盖，给个空方法
    {
    }

    public function index()
    {
        $isLogin = $this->isLogin();
        if ($isLogin) {
            return $this->redirect('index/index');
        } else {
            //如果后台用户已经登陆，需要跳跳转首页
            return $this->fetch();
        }
    }

    /**
     * 登陆
     */
    public function check()
    {
        if (request()->isPost()) {
            $data = input('post.');
            if (!captcha_check($data['code'])) {
                $this->error('验证码错误');
            }
            $validate = validate('AdminUser');
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }

            try {
                $user = model('AdminUser')->get(['username' => $data['username']]);
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
            if (!$user || $user->status != config('code.status_normal')) {
                $this->error('用户不存在');
            }
            //对密码进行判断
            if (IAuth::setPassword($data['password']) != $user['password']) {
                $this->error(IAuth::setPassword($data['password']));
            }
            $udata = [
                'last_login_time' => time(),
                'last_login_ip' => request()->ip(),
            ];
            try {
                model('AdminUser')->save($udata, ['id' => $user->id]);
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }

            session(config('admin.session_user'), $user, config('admin.session_user_scope'));

            return $this->success('登陆成功', 'index/index');
        } else {
            $this->error('请求不合法');
        }

    }


    public function loginout()
    {
        \session(null, config('admin.session_user_scope'));
        $this->redirect('login/index');
    }

}